// 导入express模块
var express = require("express");
var fs = require("fs");
var template = require('../template.js');
var public = require("../public.js");
var db = require("../db/db.js");

// 生成路由
var router = express.Router();


// 用户提交问题 地址
router.get('/user/ask', public.isLogin, (req, res) => {
  res.render("ask",{
    title: "提问-问答系统",
    privateJs:"ask"
  })
});
// 用户提交问题
router.post('/api/user/ask', public.isLogin, (req, res) => {
  // console.log(req.body);
  var question = {};
  // 格式ip的
  function formatIp(val) {
    // ::ffff:192.168.3.251
    // ::1
    val = val == "::1" ? "192.168.0.1" : val;
    if (val.startsWith("::ffff:")) {
      val = val.substr(7);
    }
    console.log(val);
    return val;
  }
  question.text = req.body.content;
  question.createUser = req.cookies._id;
  question.ip = formatIp(req.ip);
  question.createTime = new Date().getTime();
  console.log(question)
  console.log(req.cookies._id);
  // 写入数据
  new db.Question(question).save(function(err){
    if(!err){
      res.status(200).json({ code: "success", content: "提问成功！" })
    }
  })
});
// 用户回答问题 地址
router.get('/user/answer', public.isLogin, (req, res) => {
  res.render("answer",{
    title: "回答-问答系统",
    privateJs:"answer"
  })
});
// 用户回答问题
router.post('/api/user/answer', public.isLogin, (req, res) => {
  // console.log(req.body);
  // 回答的对象
  var answer={}
  answer.text = req.body.content;
  answer.question = req.cookies.querstion;
  answer.ip = req.ip;
  answer.createTime = new Date().getTime();
  answer.createUser=req.cookies._id;
  // console.log(answer.querstion);
  new db.Answer(answer).save((err,data)=>{
    if(!err){
      // 写入question集合 更新answers数组里 增加一个answer表里的id
      var id=answer.question;
      var answerd={$push:{answers:data.id}}
      db.Question.findByIdAndUpdate(id,answerd,function(){
        if(!err){
            res.status(200).json({ code: "success", content: "回答问题成功！" })

        }
      })

    }
  })

  
});

module.exports = router;